package com.hospital.hospitalserver.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 诊断记录编号生成器
 * 编码结构：DRC + 日期(yyyyMMdd) + appointment_id后六位
 */
public class DiagnosisRecordNoGenerator {

    private static final String PREFIX = "DRC";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * 生成诊断记录编号
     * @param appointmentId 预约ID
     * @return 诊断记录编号
     */
    public static String generateRecordNo(String appointmentId) {
        // 获取当前日期
        String dateStr = LocalDateTime.now().format(DATE_FORMATTER);

        // 处理appointment_id后六位
        String appointmentSuffix = processAppointmentId(appointmentId);

        return PREFIX + dateStr + appointmentSuffix;
    }

    /**
     * 处理appointment_id，取后六位，不足补零
     * @param appointmentId 预约ID
     * @return 处理后六位字符串
     */
    private static String processAppointmentId(String appointmentId) {
        if (appointmentId == null) {
            throw new IllegalArgumentException("appointmentId cannot be null");
        }

        String idStr = String.valueOf(appointmentId);

        if (idStr.length() <= 6) {
            // 不足6位，前面补零
            return String.format("%06d", appointmentId);
        } else {
            // 超过6位，取后6位
            return idStr.substring(idStr.length() - 6);
        }
    }

    /**
     * 带校验的生成方法（推荐使用）
     * @param appointmentId 预约ID
     * @param visitId 就诊ID（用于校验）
     * @return 诊断记录编号
     */
    public static String generateRecordNoWithCheck(String appointmentId, Integer visitId) {
        if (appointmentId == null) {
            throw new IllegalArgumentException("appointmentId cannot be null");
        }
        if (visitId == null) {
            throw new IllegalArgumentException("visitId cannot be null");
        }

        return generateRecordNo(appointmentId);
    }
}